﻿package bdz.common.utils
{
	import bdz.common.managers.ModuleAssetManager;	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.system.ApplicationDomain;
	
	public class ExternalUIFactory extends EventDispatcher {
		private static var instance:ExternalUIFactory;
		private static var assetLoader:ModuleAssetManager;
		public var loaded:Boolean = false;
		public var url:String = "";
		
		public function ExternalUIFactory(se:SingletonEnforcer) {
			super();
		}
		public static function getInstance():ExternalUIFactory{
			if(instance == null){
				instance = new ExternalUIFactory(new SingletonEnforcer());
				instance.initialize();	
			}
			return instance;
		} 
		private function initialize():void{
			assetLoader = new ModuleAssetManager(ApplicationDomain.currentDomain);
			assetLoader.addEventListener(Event.COMPLETE, onExternalLoaded);
			assetLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			assetLoader.url = url;
		}
		private function onIOError(evt:IOErrorEvent):void{
			dispatchEvent(evt);
		}
		private function onExternalLoaded(evt:Event):void{
			loaded = true;
			dispatchEvent(evt);
		}
		public function getUIWithLinkage(str:String):Object{
			if(!loaded) return null;
			return assetLoader.retrieveClass(str);
		}
		public function manualLoad(str:String):void{
			if(assetLoader == null){
				assetLoader = new ModuleAssetManager(ApplicationDomain.currentDomain);
				assetLoader.addEventListener(Event.COMPLETE, onExternalLoaded);
				assetLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			}
			assetLoader.url = str;
		}
	}
}
internal class SingletonEnforcer {}